package com.example.mp3play;


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button playbtn,stopbtn;
    private Button nextbtn,prevbtn;
    private Button scanbtn,pausebtn;
    private SeekBar timebar;
    private TextView mptv,timeView;
    private List<Music> mData = null;
    private Context mContext;
    private musicAdapter mAdapter = null;
    private ListView musiclist;
    public MediaPlayer player=new MediaPlayer();; // 定义多媒体对象
    private int songnum=0;
    private ArrayList<String> music;
    private SimpleDateFormat time = new SimpleDateFormat("m:ss");
    private Handler myHandler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mContext = MainActivity.this;
        mData = new LinkedList<Music>();
        playbtn=(Button) findViewById(R.id.playBtn);
        stopbtn=(Button) findViewById(R.id.stopBtn);
        prevbtn=(Button) findViewById(R.id.previousBtn);
        nextbtn=(Button) findViewById(R.id.nextBtn);
        pausebtn=(Button) findViewById(R.id.pauseBtn);
        mptv=(TextView)findViewById(R.id.mpTv);
        musiclist=(ListView)findViewById(R.id.MusicList);
        timeView = findViewById(R.id.timeTextView);
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            //这里会调用后面的onRequestPermissionResult
        }else{
            scan();
            player=MediaPlayer.create(MainActivity.this,Uri.parse(music.get(0)));
        }
        musiclist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                songnum=position;
                player.stop();
                player.reset();
                player = MediaPlayer.create(MainActivity.this, Uri.parse(music.get(songnum )));
                mptv.setText("正在播放："+mData.get(songnum).getName());
                player.seekTo(0);
                player.start();
            }
        });
        playbtn.setOnClickListener(this);
        stopbtn.setOnClickListener(this);
        pausebtn.setOnClickListener(this);
        prevbtn.setOnClickListener(this);
        nextbtn.setOnClickListener(this);
        timebar=findViewById(R.id.seekbar);
        //拖动进度条时应该发生的事情
        timebar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //如果不判断是否来自用户操作进度条，会不断执行下面语句块里面的逻辑
                if(fromUser){
                    player.seekTo(seekBar.getProgress());
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        myHandler.post(updateUI);
    }
    @Override
    //拒绝权限获取则直接关闭程序
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
        switch (requestCode){
            case 1:
            {
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    scan();
                    player=MediaPlayer.create(MainActivity.this,Uri.parse(music.get(0)));
                }else{
                    Toast.makeText(this,"拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            }
            default:
                break;
        }
    }
    private Runnable updateUI = new Runnable() {
        @Override
        public void run() {
            timebar.setMax(player.getDuration());
            if(player.isPlaying()){
                mptv.setText("正在播放："+mData.get(songnum).getName());
                timeView.setText(time.format(player.getCurrentPosition())+"/"+time.format(player.getDuration()));
            }
            //获取歌曲进度并在进度条上展现
            timebar.setProgress(player.getCurrentPosition());
            //获取播放位置
            myHandler.postDelayed(updateUI,100);
            player.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    next();
                }
            });
        }

    };
    private void play(){
        player.reset();
        if(songnum<music.size()-1){
            try {
                player.setDataSource(music.get(songnum+1));
                mptv.setText(mData.get(songnum).getName());
                player.prepare();
                player.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            songnum=0;
            try {
                player.setDataSource(music.get(songnum));
                player.prepare();
                player.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.playBtn:
                playm();
                break;
            case R.id.pauseBtn:
               pausem();
                break;
            case R.id.stopBtn:
               stopm();
                break;
            case R.id.previousBtn:
                previous();
                break;
            case R.id.nextBtn:
                next();
                break;

        }
    }
    public void playm(){
        if(player!=null){
            player.start();
            //mPlayer.setVolume(1.0f,1.0f);
            //mPlayer.setLooping(true);
        }
    }
    public void pausem(){
        player.pause();     //停止播放
        mptv.setText("暂停播放："+mData.get(songnum).getName());
    }
    public void stopm(){
        player.stop();
        try {
            player=MediaPlayer.create(MainActivity.this, Uri.parse(music.get(songnum )));
            mptv.setText("停止播放："+mData.get(songnum).getName());
            timeView.setText(time.format(player.getCurrentPosition())+"/"+time.format(player.getDuration()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void previous(){
        if(player != null && songnum > 0) {
            player.stop();
            player.reset();
            player = MediaPlayer.create(MainActivity.this, Uri.parse(music.get(songnum - 1)));
            mptv.setText("正在播放："+mData.get(songnum-1).getName());
            songnum--;
            player.seekTo(0);
            player.start();
        }else {
            songnum=music.size()-1;
            player.stop();
            player.reset();
            player = MediaPlayer.create(MainActivity.this, Uri.parse(music.get(songnum)));
            mptv.setText("正在播放："+mData.get(songnum).getName());
            player.seekTo(0);
            player.start();
        }
    }
    public void next(){
        if(player != null && songnum < music.size()-1) {
            player.stop();
            player.reset();
            player=MediaPlayer.create(MainActivity.this,Uri.parse(music.get(songnum+1)));
            mptv.setText("正在播放："+mData.get(songnum+1).getName());
            songnum++;
            player.seekTo(0);
            player.start();
        }else {
            songnum=0;
            player.stop();
            player.release();
            player=MediaPlayer.create(MainActivity.this,Uri.parse(music.get(0)));
            mptv.setText("正在播放："+mData.get(0).getName());
            player.seekTo(0);
            player.start();
        }
    }
    public void scan(){
        music=new ArrayList<>();
        //File file=new File(String.valueOf(Environment.getExternalStorageDirectory())+"/Music");
        File file=new File("/sdcard/Music");

        File[] files =file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                int i=name.lastIndexOf(".");
                name=name.substring(i);
                if(name.equalsIgnoreCase(".mp3")){
                    return true;
                }else return false;
            }
        });
        mData = new LinkedList<Music>();
        for(int i=0;i<files.length;i++){
            File f=new File(file.getAbsolutePath()+"/"+files[i].getName());
            music.add(f.getAbsolutePath());
            mData.add(new Music(f.getName()));
        }
        mAdapter = new musicAdapter((LinkedList<Music>) mData, mContext);
        musiclist.setAdapter(mAdapter);
    }
}
